package freespiritsocial.io.user.ui.fragment.post

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.MotionEvent
import android.view.View
import android.view.ViewStub
import android.widget.ImageView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.data.model.bean.PostPojo
import freespiritsocial.io.user.databinding.FrgExplorePostDetailItemBinding
import freespiritsocial.io.user.databinding.ViewStubBannerBinding
import freespiritsocial.io.user.databinding.ViewStubVideoBinding
import freespiritsocial.io.user.ext.initDefIndicator
import freespiritsocial.io.user.ext.loadImage
import freespiritsocial.io.user.handle.BackHandle
import freespiritsocial.io.user.ui.adapter.PostImagesAdapter
import freespiritsocial.io.user.ui.fragment.message.SharePostListDialogFragment
import freespiritsocial.io.user.ui.fragment.mine.MineFrg
import freespiritsocial.io.user.ui.helper.PostMoreDialogHelper
import freespiritsocial.io.user.viewmodel.PostDetailViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @description 帖子详情Item
 */
class ExplorePostDetailItemFrg: BaseFragment<PostDetailViewModel,FrgExplorePostDetailItemBinding>() {

    override fun layoutId(): Int = R.layout.frg_explore_post_detail_item
    private val imagesAdapter by lazy(LazyThreadSafetyMode.NONE) {
        PostImagesAdapter(data.fileList)
    }

    private val commentDialogFragment by lazy(LazyThreadSafetyMode.NONE) {
        CommentDialogFragment.crate(mViewModel,this)
    }
    var videoPlayer: StandardGSYVideoPlayer? = null
    private lateinit var data: PostPojo
    private var position: Int = 0

    companion object {
        const val TAG = "ExplorePostDetailItemFrg"
        fun create(data: PostPojo,position: Int) =
            ExplorePostDetailItemFrg().also {
                it.data = data
                it.position = position
            }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        mViewModel.data.value = data
        model = mViewModel
        click = Click()
        tvDescribe.movementMethod = ScrollingMovementMethod.getInstance()
        tvDescribe.setOnTouchListener { v,event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                v.parent.requestDisallowInterceptTouchEvent(true)
            }
            if (event.action == MotionEvent.ACTION_MOVE) {
                v.parent.requestDisallowInterceptTouchEvent(true)
            }
            if (event.action == MotionEvent.ACTION_UP) {
                v.parent.requestDisallowInterceptTouchEvent(false)
            }
            false
        }
        stubBannerImages.viewStub?.setOnInflateListener(::initBanner)
        stubBannerVideo.viewStub?.setOnInflateListener(::initPlayer)
        if (data.isVideo) {
            stubBannerVideo.viewStub?.inflate()
        } else {
            stubBannerImages.viewStub?.inflate()
        }
        return@with
    }

    private fun initBanner(stub: ViewStub,inflated: View) {
        val dataViewStub: ViewStubBannerBinding = DataBindingUtil.bind(inflated) ?: return
        dataViewStub.bannerImages.initDefIndicator(requireContext())
        dataViewStub.bannerImages.isAutoPlay = false
        dataViewStub.bannerImages.adapter = imagesAdapter
    }

    private fun initPlayer(stub: ViewStub,inflated: View) {
        val dataViewStub: ViewStubVideoBinding = DataBindingUtil.bind(inflated) ?: return
        videoPlayer = dataViewStub.videoPlayer
        videoPlayer?.thumbImageView = ImageView(requireContext()).apply {
            loadImage(data.coverUrl)
        }
        videoPlayer?.isLooping = true
        dataViewStub.videoPlayer.canToggleUI = true
        videoPlayer?.setUpLazy(data.fileUrl,true,null,null,"")
        videoPlayer?.backButton?.isVisible = false
        videoPlayer?.fullscreenButton?.isVisible = false
        //是否可以滑动调整
        videoPlayer?.setIsTouchWiget(false)
        videoPlayer?.playTag = TAG
        videoPlayer?.playPosition = position
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.commentResult.observe(this) {
            commentDialogFragment.setData(it.data,it.isRefresh)
        }
        eventViewModel.playPosition.observe(this) {
            if (it == position)
                videoPlayer?.startPlayLogic()
            else
                videoPlayer?.onVideoPause()
        }

        //这里跟Explore用的是一份数据 所以同步刷新
        eventViewModel.savePostEvent.observe(this) {
            if (data.invitationId == it) {
                mViewModel.data.value = data
            }
        }
        eventViewModel.hidePostEvent.observe(this) {
            if (data.invitationId == it) {
                nav().navigateUp()
            }
        }
        eventViewModel.delPostEvent.observe(this) {
            if (data.invitationId == it) {
                nav().navigateUp()
            }
        }
        eventViewModel.likePostEvent.observe(this) {
            if (data.invitationId == it) {
                mViewModel.data.value = data
            }
        }
    }

    inner class Click: BackHandle {
        override fun goBack() {
            nav().navigateUp()
        }

        fun share() {
            SharePostListDialogFragment.crate(this@ExplorePostDetailItemFrg,data).show(childFragmentManager,"share")
        }

        fun like() {
            mViewModel.likePost(data.invitationId)
        }

        fun openComment() {
            commentDialogFragment.show(childFragmentManager,"csw")
        }

        fun more() {
            PostMoreDialogHelper(this@ExplorePostDetailItemFrg,mViewModel.data.value!!,mViewModel).create()
        }

        fun goToPeopleHome() {
            if (data.advertisersId != null) return
            mViewModel.getUserInfo(data.userId) {
                nav().navigateAction(R.id.mineFrg,bundleOf(MineFrg.KEY_IS_USER to false,MineFrg.KEY_USER to it))
            }
        }
    }
}